package com.demo.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.api.IErrorCode;
import com.baomidou.mybatisplus.extension.enums.ApiErrorCode;
import com.baomidou.mybatisplus.extension.exceptions.ApiException;
import com.demo.domain.SysMenu;
import com.demo.feign.JwtToken;
import com.demo.feign.OAuth2FeignClient;
import com.demo.model.LoginResult;
import com.demo.service.SysLoginService;
import com.demo.service.SysMenuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
//import org.springframework.security.core.authority.SimpleGrantedAuthority;
//import org.springframework.security.jwt.Jwt;
//import org.springframework.security.jwt.JwtHelper;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SysLoginServiceImpl implements SysLoginService {

    /**
     * 远程调用 获取token的方法
     */
    @Autowired
    private OAuth2FeignClient oAuth2FeignClient;

    @Value("${basic.token:Basic Y29pbi1hcGk6Y29pbi1zZWNyZXQ=}")
    private String basicToken;

    @Autowired
    private SysMenuService sysMenuService;

    /**
     *
     * @param username
     * @param password
     * @return
     */
    @Override
    public LoginResult login(String username, String password) {
        log.info("用户{}开始登录",username);
        //1.需要token 需要远程调用 authorizotion-server服务

        String token="";
        //普通用户ResponseEntity<JwtToken> tokenResponseEntity = oAuth2FeignClient.getToken("password", username, password, "member_type", basicToken);
        ResponseEntity<JwtToken> tokenResponseEntity = oAuth2FeignClient.getToken("password", username, password, "admin_type", basicToken);//管理员用户
        if(HttpStatus.OK != tokenResponseEntity.getStatusCode()){
            throw new ApiException(ApiErrorCode.FAILED);
        }
        JwtToken jwtToken = tokenResponseEntity.getBody();
        log.info("远程调用授权服务器成功,获取的token为{}", JSON.toJSONString(jwtToken,true));

        token = jwtToken.getAccessToken();
        //2.需要菜单信息 根据用户查询菜单数据
        //解析jwttoken
        Jwt jwt = JwtHelper.decode(token);
        String json = jwt.getClaims();
        JSONObject jwtJson = JSON.parseObject(json);
        Long userId =Long.valueOf(jwtJson.getString("user_name")) ;
        List<SysMenu> menus = sysMenuService.getMenusByUserId(userId);

        //3.需要权限信息 根据用户查询菜单数据


        JSONArray jsonArray = jwtJson.getJSONArray("authorities");
        List<SimpleGrantedAuthority> authorities = jsonArray.stream() //组装我们的权限数据
                                                    .map(authorityJson->new SimpleGrantedAuthority(authorityJson.toString()))
                                                    .collect(Collectors.toList());
        return new LoginResult(token,menus,authorities);

    }
}
